package logic

import (
	"context"
	"fmt"
	"group/cache"
	"group/model"
	"group/pkg"

	"group/grouprpc/grouprpc"
	"group/grouprpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *grouprpc.RegisterRequest) (*grouprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	if in.CaptchaCode == "" || in.Password == "" || in.Account == "" || in.SendSms == "" {
		return nil, fmt.Errorf("用户名密码和验证码不能为空")
	}
	var user model.User
	model.DB.Where("account=?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("用户已注册")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if result != in.CaptchaCode {
		return nil, fmt.Errorf("验证码错误")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "sms"+in.Account).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	user = model.User{
		Account:  in.Account,
		Password: pkg.Md5sre(in.Password),
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &grouprpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
